﻿using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace SimpleX.Tracing
{
    public static class TracingServiceExtensions
    {
        public static IServiceCollection AddTracingServices(this IServiceCollection services, string applicationName)
        {
            // 添加 TraceId 管理器
            services.AddSingleton<ITraceIdManager, TraceIdManager>();

            // 添加 HttpContext 访问器
            services.AddHttpContextAccessor();

            // 添加埋点服务
            services.AddSingleton<ActivitySource>(new ActivitySource(applicationName));
            services.AddScoped<ITracingService, TracingService>();

            return services;
        }

        public static IApplicationBuilder UseTracing(this IApplicationBuilder app)
        {
            // 添加追踪中间件
            app.UseMiddleware<TracingMiddleware>();

            return app;
        }

        // 扩展方法：在控制器中快速获取当前 TraceId
        public static string GetTraceId(this ControllerBase controller)
        {
            return controller.HttpContext.Items["TraceId"] as string;
        }
    }
}
